package com.yw.atp.action;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.yw.atp.model.AtpImage;
import com.yw.atp.model.Command;
import com.yw.atp.model.Department;
import com.yw.atp.model.IDEntity;
import com.yw.atp.model.Profession;
import com.yw.atp.model.Staff;
import com.yw.atp.service.CommandService;
import com.yw.atp.service.PersistenceService;
import com.yw.atp.service.StaffService;
import com.yw.atp.util.BeanUtil;
import com.yw.atp.util.Constants;
import com.yw.atp.util.ImageUtil;
import com.yw.atp.util.PushUtil;
import com.yw.atp.util.StringUtil;
import com.yw.atp.web.ActionBase;

@Scope("prototype")
@Component("commandAction")
public class CommandAction extends ActionBase implements ServletRequestAware{
	private static final long serialVersionUID = 1L;
	@Autowired
	private PersistenceService service;
	@Autowired
    private CommandService commandService;
	@Autowired
	private StaffService staffService;
	HttpServletRequest request;
	public List<Command> commandList;
	public String commandIds;
	public Command command;
	public Staff staff;
	public Department deprt;
	public Profession profe;
	public List<Department> departmentList;
	public List<Profession> professionList;
	public List<Staff> staffList;
	public String staIds;
	public String depIds;
	public String proIds;
	public String res;
	public int start = 0;
	public int limit = 20;
    public boolean top;
	private File imgFile;  
    // 上传文件名  
    private String imgFileFileName;  
    // 上传文件类型  
    private String imgFileContentType;
    //纬度
    private String latitude;
    //经度
    private String longitude;
	//类型 0:指挥中心 ; 1:重要通告; 2:我来找茬
    private String commType = "1";
	
	public String list(){
		try {
			JSONObject js = new JSONObject();
			if(staff!=null&&staff.getMobileID()!=null&&!"".equals(staff.getMobileID())){
				if(command==null)command = new Command();
				command.setCommType(commType);
				commandList = commandService.getCommands(command,staff.getMobileID());
				js.put("totalCount",commandList.size());
				js.put("topics",Command.capture(commandList));
			}else{
				if(command==null)command = new Command();
				int len = (int)commandService.getCommandsCount(command,null,null,commType);
				System.out.println("--------len---------"+len);
				start = start>(len-1)?(len-1):start;
				limit = limit>(len-start)?(len):(start+limit);
				commandList = commandService.getCommands(command,null,null,commType,start,limit);
				System.out.println("--------commandList len ---------"+commandList.size());
				if(commandList!=null&&commandList.size()>0){
					js.put("totalCount",len);
					if(!"2".equals(commType)){
						for(Command c:commandList){
							String sc = String.valueOf(staffService.getStaffsCount(c));
							String rc = String.valueOf(staffService.getReplyCount(c));
							c.setReplyStatus(rc+"/"+sc);
						}
					}
					js.put("topics",Command.capture(commandList));
				}
			}
			res = js.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String add(){
		if(command!=null){
			command.setCommType(commType);
		}
		if(command!=null&&staff!=null&&staff.getMobileID()!=null){
			Staff sender = staffService.findByMobile(staff.getMobileID());
			command.setSender(sender);
			command.setIssuer(sender);
		}
		
		if(StringUtil.checkCommand(command,staIds,depIds,proIds)){
			if(command.getIssuer()!=null&&command.getIssuer().getId()==null){command.setIssuer(null);}
			Set<Staff> sList = null;
			Set<Department> dList = null;
			Set<Profession> pList = null;
			
			
			if(latitude!=null)command.setLatitude(latitude);
			if(longitude!=null)command.setLongitude(longitude);
			
			if(imgFile!=null){
				AtpImage ai = new AtpImage();
				ai.setPath(ImageUtil.saveFile(imgFile,ServletActionContext.getServletContext().getRealPath("/upload"),this.getImgFileFileName()));
				service.save(ai);
				command.setAtpImage(ai);
			}
			
			fillList(sList,staIds,0);
			fillList(dList,depIds,1);
			fillList(pList,proIds,2);
			
			
			if(command.getId()!=null&&command.getId().intValue()>0){
				Command c = service.load(command);
				c.setDeparList(command.getDeparList());
				c.setProList(command.getProList());
				c.setStaffList(command.getStaffList());
				c.setStatus(Constants.COMMAND_STATUS_YZF);
				c.setUpdateAt(new Date());
				service.save(c);
				
				command.setCommType("3");
				command.setId(null);
				command.setStatus(Constants.COMMAND_STATUS_NEW);
				command.setTop(c.isTop());
				command.setContent(c.getContent());
				command.setAtpImage(c.getAtpImage());
				command.setIssueTime(new Date());
				command.setSendTime(new Date());
				command.setIssuer(c.getIssuer());
				command.setSender(c.getSender());
				service.save(command);
				
			}else{
				if(command.getSendTime()==null)command.setSendTime(new Date());
				if(command.getIssueTime()==null)command.setIssueTime(new Date());
				if(command.getCreatedAt()==null)command.setCreatedAt(new Date());
				service.save(command);
			}
			System.out.println("------------begin push");
			if(true||(sList!=null&&sList.size()>0)||(dList!=null&&dList.size()>0)||(pList!=null&&pList.size()>0)){
				List<Staff> staffList = staffService.getStaffs(command);
				System.out.println("staffList 有 "+ (staffList!=null?staffList.size():"0") + "消息需要 Push");
				if(staffList!=null){
					for(Staff staff:staffList){
						if(command.getSender()!=null&&command.getSender().getId()!=null&&staff.getId().intValue() != command.getSender().getId().intValue()){
							try {
								boolean isGet = false;
								System.out.println("开始给 "+staff.getName()+ " Push "+("1".equals(command.getCommType())?"重要信息":"我来找茬"));
								PushUtil.polling(staff.getMobileID(),command.getCommType()+"_"+(isGet?"0":"1"),BeanUtil.formatCommand(command,null),isGet);
							} catch (Exception e){
								System.out.println("Push 异常 : " + e.getMessage());
							}
						}
					}
				}
			}
			return SUCCESS;
		}
		return INPUT;
	}
	
	public void fillList(Set set,String idstr,int model){
		if(idstr!=null){
			String[] ids = idstr.split(",");
			if(ids!=null&&ids.length>0){
				set = new HashSet<Profession>();
				for(int i=0;i<ids.length;i++){
					int id ;
					try{
						id = Integer.valueOf(ids[i]);
					}catch(Exception e){
						id = 0;
					}
					if(ids[i]!=null&&id>0){
						IDEntity en = new Department();
						switch(model){
							case 0:en=new Staff();break;	
							case 1:en=new Department();break;
							case 2:en=new Profession();break;
						}
						en.setId(id);
						en = service.load(en);
						if(en!=null&&en.getId()!=null&&en.getId().intValue()>0){
							set.add(en);
						}
					}
				}
				if(set.size()>0){
					switch(model){
						case 0:command.setStaffList(set);break;
						case 1:command.setDeparList(set);break;
						case 2:command.setProList(set);break;
					}
				}
			}
		}
	}
	
	public String del(){
		if(commandIds!=null&&!"".equals(commandIds)){
			service.remove(Command.class.getName(),commandIds);
		}
		return SUCCESS;
	}
	
	public String status(){
		if(command!=null&&StringUtil.checkID(command.getId())&&StringUtil.isNotNull(command.getStatus())){
			service.updateStatus(Command.class.getName(),String.valueOf(command.getId()),command.getStatus());
			return SUCCESS;
		}
		return INPUT;
	}
	
	public String setTop(){
		if(commandIds!=null&&commandIds.length()>0){
			commandService.setTop(commandIds,isTop());
		}
		return SUCCESS;
	}
	
	public void setServletRequest(HttpServletRequest request) {
        if(request==null){
            request = ServletActionContext.getRequest();
        }
        this.request = request;
    }
	
	public PersistenceService getService() {
		return service;
	}
	
	public void setService(PersistenceService service) {
		this.service = service;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	public Department getDeprt() {
		return deprt;
	}
	
	public void setDeprt(Department deprt) {
		this.deprt = deprt;
	}
	
	public Profession getProfe() {
		return profe;
	}
	
	public void setProfe(Profession profe) {
		this.profe = profe;
	}
	
	public List<Department> getDepartmentList() {
		return departmentList;
	}
	
	public void setDepartmentList(List<Department> departmentList) {
		this.departmentList = departmentList;
	}
	
	public List<Profession> getProfessionList() {
		return professionList;
	}
	
	public void setProfessionList(List<Profession> professionList) {
		this.professionList = professionList;
	}
	public Staff getStaff() {
		return staff;
	}

	public void setStaff(Staff staff) {
		this.staff = staff;
	}
	public List<Command> getCommandList() {
		return commandList;
	}

	public void setCommandList(List<Command> commandList) {
		this.commandList = commandList;
	}

	public Command getCommand() {
		return command;
	}

	public void setCommand(Command command) {
		this.command = command;
	}
	public String getRes() {
		return res;
	}

	public void setRes(String res) {
		this.res = res;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}
	public boolean isTop() {
		return top;
	}

	public void setTop(boolean top) {
		this.top = top;
	}
	
	public String getCommandIds() {
		return commandIds;
	}

	public void setCommandIds(String commandIds) {
		this.commandIds = commandIds;
	}
	public CommandService getCommandService() {
		return commandService;
	}

	public void setCommandService(CommandService commandService) {
		this.commandService = commandService;
	}
	public List<Staff> getStaffList() {
		return staffList;
	}

	public void setStaffList(List<Staff> staffList) {
		this.staffList = staffList;
	}

	public File getImgFile() {
		return imgFile;
	}

	public void setImgFile(File imgFile) {
		this.imgFile = imgFile;
	}

	public String getImgFileFileName() {
		return imgFileFileName;
	}

	public void setImgFileFileName(String imgFileFileName) {
		this.imgFileFileName = imgFileFileName;
	}

	public String getImgFileContentType() {
		return imgFileContentType;
	}

	public void setImgFileContentType(String imgFileContentType) {
		this.imgFileContentType = imgFileContentType;
	}
	
	public String getLatitude() {
		return latitude;
	}

	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public String getCommType() {
		return commType;
	}

	public void setCommType(String commType) {
		this.commType = commType;
	}
	
	public StaffService getStaffService() {
		return staffService;
	}

	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}
}
